<template>
  <div class="postPublish">
    <!-- 标题 -->
    <el-row class="title">
      <el-col :span="1">
        <div class="grid-content bg-purple" style="line-height:36px">标题</div>
      </el-col>
      <el-col :span="23">
        <div class="grid-content bg-purple-light">
          <input type="text" placeholder="请输入标题" v-model="form.title" />
        </div>
      </el-col>
    </el-row>

    <!-- 内容 -->
    <el-row>
      <el-col :span="1">
        <div class="grid-content bg-purple" style="line-height:30px">内容</div>
      </el-col>
      <el-col :span="23">
        <div class="grid-content bg-purple-light">
          <!-- :useCustomImageHandler="true" 使用自定义的图片处理器 -->
          <!-- @image-added="ImageAdded" 声明图片选择完毕后的处理函数 -->
          <!-- v-model="content" 将绑定content里的内容或数据属性 -->
          <vue-editor
            v-model="form.content"
            :useCustomImageHandler="true"
            @image-added="ImageAdded"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 栏目 -->
    <el-row class="part">
      <el-col :span="1">
        <div class="grid-content bg-purple" style="line-height:36px">栏目</div>
      </el-col>
      <el-col :span="23">
        <div class="grid-content bg-purple-light part_checkbox">
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in categoriesList"
              :key="item.id"
              :label="item.id"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-col>
    </el-row>

    <!-- 封面 -->
    <el-row class="cover">
      <el-col :span="1">
        <div class="grid-content bg-purple" style="line-height:30px">封面</div>
      </el-col>
      <el-col :span="23">
        <div class="grid-content bg-purple-light cover_box">
          <el-upload
            :action="$axios.defaults.baseURL + '/upload'"
            :headers="{Authorization :'Bearer ' + token}"
            :on-success="coverSuccess"
            :on-remove="coverRemove"
            :file-list="form.cover"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </el-col>
    </el-row>

    <!-- 类型 -->
    <el-row class="types">
      <el-col :span="1">
        <div class="grid-content bg-purple" style="line-height:36px">类型</div>
      </el-col>
      <el-col :span="23">
        <div class="grid-content bg-purple-light type">
          <el-radio v-model="radio" label="1">文章</el-radio>
          <el-radio v-model="radio" label="2">视频</el-radio>
        </div>
      </el-col>
    </el-row>

    <!-- 提交按钮 -->
    <el-row>
      <el-col :span="1">
        <div class="grid-content bg-purple"></div>
      </el-col>
      <el-col :span="23">
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="submit">提交</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  components: {
    VueEditor
  },

  data() {
    return {
      type: [],
      token: localStorage.getItem("userToken"),
      radio: "1",
      categoriesList: [],
      checkList: [],
      form: {
        title: "",
        content: "",
        categories: [
          // 数组里的每个元素都是对象
          // 里面有id属性
        ],
        cover: [],
        type: 1
      }
    };
  },

  created() {
    this.loadCategory();

    if (this.$route.query.id) {
      // 如果url带上了id 证明是修改文章
      this.loadPost();
    }
  },

  watch: {
    checkList() {
      // console.log('checkList',this.checkList);
      this.form.categories = this.checkList.map(item => {
        return { id: item };
      });
    }
  },

  methods: {
    ImageAdded(file, Editor, cursorLocation, resetUploader) {
      // 这里是富文本框选择完图片会触发的函数
      // file：选中的图片   Editor：当前编辑器实例对象
      // cursorLocation：当前光标所在的位置
      // resetUploader：上传完图片用来重新初始化上传功能的函数
      // 1. 上传图片
      let formData = new FormData();

      formData.append("file", file);
      // 3.拿到图片地址要放入富文本框当中
      this.$axios({
        url: "/upload",
        method: "POST",
        data: formData
      }).then(res => {
        console.log("文件上传返回的结果", res);
        const url = this.$axios.defaults.baseURL + res.data.data.url;

        // Editor.insertEmbed() 是编辑器自带函数，可以往编辑器内加入内容
        Editor.insertEmbed(cursorLocation, "image", url);
        // 将图片插入到富文本框后还要重置上传功能
        resetUploader();
      });
    },

    loadCategory() {
      this.$axios({
        url: "/category"
      }).then(res => {
        console.log("栏目列表返回结果", res);

        // 过滤掉关注和头条两项，使用数组过滤方法
        // 因为这两项是自动生成的
        this.categoriesList = res.data.data.filter(item => {
          return item.id != 0 && item.id != 999;
        });

        console.log(this.categoriesList);
      });
    },

    loadPost() {
      this.$axios({
        url: "/post/" + this.$route.query.id
      }).then(res => {
        console.log("111", res.data);
        this.checkList = res.data.data.categories.map(el => {
          return el.id;
        });

        // 数据里面的 cover 地址需要添加基准路径
        const newCover = res.data.data.cover.map(img => {
          const newImg = { ...img };
          if (newImg.url.indexOf("http") == -1) {
            newImg.url = this.$axios.defaults.baseURL + newImg.url;
          }
          return newImg;
        });
        res.data.data.cover = newCover;

        // 兼容旧的测试数据, 由于带有富文本框不支持的 div 标签
        // 所以需要替换成 p
        res.data.data.content = res.data.data.content.replace(/div/g, "p");

        this.form = res.data.data;
      });
    },

    coverSuccess(res, file) {
      // 上传组件成功上传可以接受三个参数
      // res 请求结果
      // file 文件本身
      // fileList 文件列表
      // 1. 需要将 file 文件放入 this.form.cover 数组里面
      // 2. 我们的封面需要 id 这个 id 是从服务器传回来的
      console.log(res.data);
      file.id = res.data.id;
      this.form.cover.push(file);
      console.log("上传封面成功");
    },

    coverRemove(file, fileList) {
      // 删除图片时可以接受两个参数
      // file 文件本身
      // FileList 文件列表
      // 这里没有请求, 也没有 id 的需求
      // 只需要将最新列表放到 form 即可
      this.form.cover = fileList;
      console.log("删除图片成功");
    },

    submit() {
      console.log(this.form);

      this.$axios({
        url: "/post",
        method: "POST",
        data: this.form
      }).then(res => {
        console.log("发布文章返回结果", res);
      });
    }
  }
};
</script>

<style lang="less" scoped>
.postPublish {
  margin-top: 26px;
}

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

.grid-content {
  min-height: 36px;
}

.title {
  input {
    border: none;
    outline: none;
    width: 380px;
    height: 34px;
    background-color: rgba(255, 255, 255, 0.4);
    text-indent: 14px;
    border-radius: 4px;
  }
}

.quillWrapper {
  width: 80%;
  background-color: rgba(255, 255, 255, 0.4);

  /deep/ .ql-editor {
    height: 100px;
  }
}

.part {
  .part_checkbox {
    display: flex;
    align-items: center;
    width: 80%;
    line-height: 40px;
    background-color: rgba(255, 255, 255, 0.4);
    padding-left: 26px;
    box-sizing: border-box;
  }
}

.cover {
  .cover_box {
    background-color: rgba(255, 255, 255, 0.4);
    padding: 10px;
    width: 80%;
    box-sizing: border-box;
  }
}

.types {
  .type {
    display: flex;
    align-items: center;
    padding-left: 10px;
    background-color: rgba(255, 255, 255, 0.4);
    width: 150px;
  }
}
</style>